package cn.lugege.org.controller;

import cn.lugege.basic.util.AjaxResult;
import cn.lugege.basic.util.PageList;
import cn.lugege.org.domain.Department;
import cn.lugege.org.query.DepartmentQuery;
import cn.lugege.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/dept")
public class DepartmentController {
    @Autowired
    private IDepartmentService service;

    @GetMapping("/{id}")
    public Department queryById(@PathVariable("id") Long id){
         return service.getById(id);
    }

    @GetMapping
    public List<Department> queryAll(){
        return service.getAll();
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
                service.del(id);
                return AjaxResult.create();
        } catch (Exception e) {
           return AjaxResult.create().setMessage("删除失败").setSuccess(false);
        }
    }
    //批量删除
    @PatchMapping
    public AjaxResult patchDelete(@RequestBody List<Long> ids){
        try {
            service.patchDelete(ids);
            return AjaxResult.create();
        } catch (Exception e) {
            return AjaxResult.create().setMessage("删除失败").setSuccess(false);
        }
    }

    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Department department){
        try {
            if(department.getId()==null){//不带id是新增操作
                service.add(department);
                System.out.println(department);
            }
            else{//更新操作
                service.upadte(department);
            }
            return AjaxResult.create();
        } catch (Exception e) {
          return new AjaxResult().setSuccess(false).setMessage("操作失败"+e.getMessage());
        }
    }

    @PostMapping
    public PageList<Department> list(@RequestBody DepartmentQuery departmentQuery){
        return service.queryData(departmentQuery);
    }

    //一对多查询
    @GetMapping("/tree")
    public List<Department> getTree(){
        return service.getTree();
    }

}
